package com.silence.whereeat.login;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.silence.whereeat.R;
import com.silence.whereeat.main.MainActivity;
import com.silence.whereeat.model.UserInfo;
import com.silence.whereeat.register.RegisterActivity;
import com.silence.whereeat.utils.CommonUrl;
import com.silence.whereeat.utils.Content;
import com.silence.whereeat.utils.HttpClientPost;

public class LoginActivity extends Activity {

    private EditText usernameEt;
    private EditText passwordEt;
    private SharedPreferences sharedPreferences;

    private int backKeyPressedTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.login);

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbgcolor));
        }

        usernameEt = (EditText) findViewById(R.id.login_username);
        passwordEt = (EditText) findViewById(R.id.login_password);
        sharedPreferences = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        Button sureBtn = (Button) findViewById(R.id.login_sure_btn);
        sureBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = usernameEt.getText().toString().trim();
                String password = passwordEt.getText().toString().trim();
                if (username.isEmpty()) {
                    usernameEt.setError("用户名不能为空！");
                } else if (password.isEmpty()) {
                    passwordEt.setError("密码不能为空！");
                } else {
                    UserInfo userInfo = new UserInfo(username, password);
                    loadToMainActivity(userInfo);
                }
            }
        });

        TextView registerTv = (TextView) findViewById(R.id.register_tv);
        String regText = "没有帐号？加入我们！";
        SpannableString spannableString = new SpannableString(regText);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        }, 0, regText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        registerTv.setText(spannableString);
        registerTv.setMovementMethod(LinkMovementMethod.getInstance());
    }

    public void loadToMainActivity(UserInfo userInfo) {

        new AsyncTask<UserInfo, Void, String>() {

            @Override
            protected String doInBackground(UserInfo... params) {
                HttpClientPost httpClientPost = new HttpClientPost(CommonUrl.URL_LOGIN);
                UserInfo userInfo = new UserInfo();
                String username = params[0].getUser_name();
                String password = params[0].getUser_password();
                userInfo.setUser_name(username);
                userInfo.setUser_password(password);
                return httpClientPost.getLoginResult(userInfo);
            }

            @Override
            protected void onPostExecute(String result) {
                if (result.equals(Content.STR_SUCCESS)) {
                    saveUserInfo();
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_LONG).show();
                }
            }
        }.execute(userInfo);
    }

    public void saveUserInfo() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String username = usernameEt.getText().toString().trim();
        String password = passwordEt.getText().toString().trim();
        editor.putString("USERNAME", username);
        editor.putString("PASSWORD", password);
        editor.putBoolean("ISCHECK", true);
        editor.apply();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && backKeyPressedTime == 0) {
            Toast.makeText(this, "再按一次返回键退出程序", Toast.LENGTH_SHORT).show();
            backKeyPressedTime = 1;
            new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        backKeyPressedTime = 0;
                    }
                }
            }.start();
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && backKeyPressedTime == 1) {
            finish();
            System.exit(0);
        }
        return true;
    }
}